/**
 * 数据验证和清理工具
 */

// 确保值是数组
export const ensureArray = (value) => {
  return Array.isArray(value) ? value : []
}

// 确保值是对象
export const ensureObject = (value) => {
  return value && typeof value === 'object' ? value : {}
}

// 清理脚本数据
export const cleanScriptData = (script) => {
  if (!script || typeof script !== 'object') {
    return {
      id: null,
      name: '未知脚本',
      description: '',
      content: '',
      language: 'unknown',
      is_active: false,
      created_at: '',
      updated_at: '',
      owner_id: null
    }
  }

  return {
    id: script.id || null,
    name: script.name || '未知脚本',
    description: script.description || '',
    content: script.content || '',
    language: script.language || 'unknown',
    is_active: Boolean(script.is_active),
    created_at: script.created_at || '',
    updated_at: script.updated_at || '',
    owner_id: script.owner_id || null,
    owner: script.owner && typeof script.owner === 'object' ? script.owner : null
  }
}

// 清理执行日志数据
export const cleanExecutionLogData = (log) => {
  if (!log || typeof log !== 'object') {
    return {
      id: null,
      script_id: null,
      user_id: null,
      status: 'unknown',
      output: '',
      error_message: '',
      executed_at: '',
      completed_at: '',
      script: null,
      user: null
    }
  }

  return {
    id: log.id || null,
    script_id: log.script_id || null,
    user_id: log.user_id || null,
    status: log.status || 'unknown',
    output: log.output || '',
    error_message: log.error_message || '',
    executed_at: log.executed_at || '',
    completed_at: log.completed_at || '',
    script: log.script && typeof log.script === 'object' ? cleanScriptData(log.script) : null,
    user: log.user && typeof log.user === 'object' ? log.user : null
  }
}

// 清理用户数据
export const cleanUserData = (user) => {
  if (!user || typeof user !== 'object') {
    return {
      id: null,
      username: '未知用户',
      email: '',
      is_active: false,
      is_superuser: false,
      created_at: ''
    }
  }

  return {
    id: user.id || null,
    username: user.username || '未知用户',
    email: user.email || '',
    is_active: Boolean(user.is_active),
    is_superuser: Boolean(user.is_superuser),
    created_at: user.created_at || ''
  }
}
